package com.zhuge_new.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.sip.SipSession;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.fence.GeoFenceClient;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapFragment;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.makeramen.roundedimageview.RoundedImageView;
import com.maning.mndialoglibrary.MToast;
import com.scwang.smartrefresh.header.waterdrop.Circle;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhuge_new.Activity.RedDisplayActivity;
import com.zhuge_new.Activity.RedpackageActivity;
import com.zhuge_new.Activity.SelectRedActivity;
import com.zhuge_new.Base.BaseFragment;
import com.zhuge_new.Dialog.RedBagDialog;
import com.zhuge_new.R;
import com.zhuge_new.bean.RedShowBean;
import com.zhuge_new.http.StringDialogCallback;
import com.zhuge_new.share.BaseHttp;
import com.zhuge_new.untils.BitmapUtils;
import com.zhuge_new.untils.DataParse;
import com.zhuge_new.untils.PreferencesUtils;
import com.zhuge_new.wxapi.Constacts;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL;

import okhttp3.internal.Util;

import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;

/**
 * Created by lenovo on 2018-08-27.
 */

public class PachedFragment extends Fragment implements View.OnClickListener, LocationSource, AMapLocationListener {

    private MapView mMapView;
    private static MapFragment fragment = null;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private OnLocationChangedListener mListener;
    private AMapLocationClient locationClient;
    private AMapLocationClientOption clientOption;
    private MarkerOptions markerOptions;
    private RedShowBean redShowBean;
    private int i;
    private String redPacketTypeId;
    private String sendRedPacketId;
    private String username;
    private IWXAPI wxApi;
    private ImageView iv_hint;
    private Bitmap bitmap;
    private String location;

    private Marker locMarker;
    private Circle ac;
    private Circle c;


    public static MapFragment newInstance() {
        if (fragment == null) {
            synchronized (MapFragment.class) {
                if (fragment == null) {
                    fragment = new MapFragment();
                }
            }
        }
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pached, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init_title(savedInstanceState, view);
    }


    public void init_title(Bundle savedInstanceState, View view) {
        LinearLayout pached_send = getActivity().findViewById(R.id.pached_send);
        ImageView iv_nav_right=getActivity().findViewById(R.id.iv_nav_right);
        ImageView share_right = getActivity().findViewById(R.id.share_right);
        share_right.setOnClickListener(this);
        pached_send.setOnClickListener(this);
        iv_nav_right.setOnClickListener(this);
        mMapView = getActivity().findViewById(R.id.MapView);
        wxApi = WXAPIFactory.createWXAPI(getActivity(), Constacts.WXAPPID);
        wxApi.registerApp(Constacts.WXAPPID);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        } else {
            if (view.getParent() != null) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        }
        markerOptions = new MarkerOptions();
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        View circle_view=View.inflate(getActivity(),R.layout.bluepoint,null);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromView(circle_view));
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        GeoFenceClient geoFenceClient=new GeoFenceClient(getActivity());
        geoFenceClient.setActivateAction(GEOFENCE_IN|GEOFENCE_OUT|GEOFENCE_STAYED);
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pached_send:

                Intent intent = new Intent(getActivity(), SelectRedActivity.class);
                intent.putExtra("location",location);
                startActivity(intent);
                break;
            case R.id.iv_nav_right:
                sharewx(0);
                break;
            case R.id.share_right:
                sharewx(1);
                break;
        }
    }

    /**
     * @@赵 0到微信好友   1到朋友圈
     */

    private void sharewx(int flag) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://web.zgzngj.com";
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "诸葛智能管家";
        msg.description = "我发现一款超级好玩的APP,赶快下载抢红包";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        msg.setThumbImage(thumb);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        wxApi.sendReq(req);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (locationClient == null) {
            locationClient = new AMapLocationClient(getActivity());
            clientOption = new AMapLocationClientOption();
            locationClient.setLocationListener(this);
            clientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//高精度定位
            //定位一次
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
            clientOption.setOnceLocationLatest(true);//设置单次精确定位
            locationClient.setLocationOption(clientOption);
            locationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                double latitude = aMapLocation.getLatitude();//获取纬度
                double longitude = aMapLocation.getLongitude(); //获取经度
                String provice=aMapLocation.getProvince();
                String city=aMapLocation.getCity();
                String district=aMapLocation.getDistrict();
                location = provice+city+district;
                red_show(latitude, longitude);
                locationClient.stopLocation();
                LatLng mylocation=new LatLng(latitude, longitude);
                aMap.addCircle(new CircleOptions().center(mylocation)
                        .fillColor(Color.argb(100, 255, 218, 185)).radius(4000)
                        .strokeColor(Color.argb(255, 255, 228, 185)).strokeWidth(5));
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }




    private void red_show(double latitude, double longitude) {
        OkGo.<String>post(BaseHttp.getRedPacket_list)
                .tag(this)
                .params("longitude", longitude)
                .params("latitude", latitude)
                .params("openId", PreferencesUtils.getString(getActivity(),"openid"))
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject obj = new JSONObject(response.body());
                            String code = obj.getString("msgcode");
                            if (code.equals("100")) {
                                redShowBean = (RedShowBean) new DataParse().getBean(response.body(), RedShowBean.class, 0);
                                marker();
                            } else {
                                String msg = obj.getString("msg");
                                MToast.makeTextShort(getContext(), msg).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    private void marker() {
        for (i = 0; i < redShowBean.getObject().getRedPoint().size(); i++) {
            Double aa = redShowBean.getObject().getRedPoint().get(i).getLongitude();
            Double bb = redShowBean.getObject().getRedPoint().get(i).getLatitude();
            LatLng latLng = new LatLng(bb, aa);

            final View view = View.inflate(getActivity(), R.layout.activity_head, null);
            bitmap = convertViewToBitmap(view);
            Marker marker = aMap.addMarker(new MarkerOptions()
                    .draggable(false)//可拖拽
                    .setFlat(false)//将Marker设置为贴地显示，可以双指下拉看效果
                       /* .icon(BitmapDescriptorFactory
                                .fromResource(R.mipmap.dituhongbao2x))//Marker图标*/
                    .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                   /* .title("marker标记")//标题*/
                    .position(latLng));

            marker.setObject(i);
            //显示InfoWindow
            if (!marker.isInfoWindowShown()) {
                marker.showInfoWindow();

            }
        }
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marke) {
                int a = (int) marke.getObject();
                redPacketTypeId = redShowBean.getObject().getRedList().get(a).getRedPacketTypeId();
                sendRedPacketId = redShowBean.getObject().getRedList().get(a).getSendRedPacketId();
                username = redShowBean.getObject().getRedList().get(a).getUserName();
                String threeHeadPhoto = redShowBean.getObject().getRedList().get(a).getThreeHeadPhoto();
                red_dialog(threeHeadPhoto);
                return false;
            }
        });

    }



    public static Bitmap convertViewToBitmap(View view) {

        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    private void red_dialog(String threeHeadPhoto) {
        final RedBagDialog redBagDialog = new RedBagDialog(getContext(), threeHeadPhoto);
        redBagDialog.setName(username);
        redBagDialog.setYesOnclickListener(new RedBagDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                OkGo.<String>post(BaseHttp.getRedEnvelopes)
                        .params("openid", "oGnL3weUJV4dDLZ6aWJXRFWn7Z6o")
                        .params("redPacketTypeId", redPacketTypeId)
                        .params("sendRedPacketId", sendRedPacketId)
                        .execute(new StringDialogCallback(getActivity()) {
                            @Override
                            public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                                if (msgCode.equals("100")) {
                                    Intent intent = new Intent(getActivity(), RedDisplayActivity.class);
                                    intent.putExtra("redPacketTypeId", redPacketTypeId);
                                    startActivity(intent);
                                    redBagDialog.dismiss();
                                }else {
                                    MToast.makeTextShort(getActivity(),msg).show();
                                }
                            }
                        });
            }
        });
        redBagDialog.onCreateView();
        redBagDialog.setUiBeforShow();
        redBagDialog.show();
    }


}